<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch">
      <el-form-item label="城市标签" prop="cityName">
        <el-select @change="getList" v-model="queryParams.cityName" placeholder="请选择">
          <el-option v-for="item in cityNameOptions" :key="item" :label="item" :value="item" />
        </el-select>
      </el-form-item>
      <el-form-item label="区域名称" prop="areaId">
        <ApiSelect
          :params="{ pageNum: 1, pageSize: 9999, cityName: cityName }"
          v-model="queryParams.areaId"
          :api="selectState.areaList.api"
          :valueField="selectState.areaList.valueField"
          :labelField="selectState.areaList.labelField"
          :resultField="selectState.areaList.resultField"
          clearable
        />
      </el-form-item>
      <el-form-item label="线路名称" prop="routeId">
        <ApiSelect
          :params="{ areaId: queryParams.areaId, enable: 1 }"
          v-model="queryParams.routeId"
          :api="selectState.route.api"
          :valueField="selectState.route.valueField"
          :labelField="selectState.route.labelField"
          clearable
        />
      </el-form-item>
      <el-form-item label="点位名称" prop="positionId">
        <ApiSelect
          :params="{ routeId: queryParams.routeId, enable: 1 }"
          v-model="queryParams.positionId"
          :api="selectState.point.api"
          :valueField="selectState.point.valueField"
          :labelField="selectState.point.labelField"
          clearable
        />
      </el-form-item>
      <el-form-item label="客服人员" prop="operationName">
        <el-input
          style="width: 214px"
          v-model="queryParams.operationName"
          placeholder="请输入客服人员"
          clearable
          @keyup.enter="handleQuery(false)"
        />
      </el-form-item>
      <el-form-item>
        <div class="btn-group">
          <el-button
            plain
            v-hasPermi="['communityData:communityData:export']"
            @click="handleExport"
          >
            导出数据
          </el-button>

          <el-radio-group v-model="radioValue" @change="handleDateRange" style="flex-shrink: 0">
            <el-radio-button label="当天" />
            <el-radio-button label="最近7天" />
            <el-radio-button label="最近30天" />
          </el-radio-group>

          <el-date-picker
            v-model="daterange"
            type="datetimerange"
            start-placeholder="开始时间"
            end-placeholder="结束时间"
            value-format="YYYY-MM-DD HH:mm:ss"
            @change="dateChange"
            :clearable="false"
            :default-time="[new Date(2000, 1, 1, 0, 0, 0), new Date(2000, 1, 1, 23, 59, 59)]"
          />
        </div>
      </el-form-item>

      <el-form-item>
        <el-button @click="handleQuery(true)">重置</el-button>
        <el-button type="primary" @click="handleQuery(false)">查询</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <div>
        列表控件：
        <el-select
          v-model="tableSelectVal"
          clearable
          multiple
          collapse-tags
          collapse-tags-tooltip
          placeholder="请选择"
          style="width: 200px"
          @change="tableSelectChange"
        >
          <el-option
            v-for="(item, index) in tableList"
            :disabled="index === 0 || index === 1 ? true : false"
            :key="item.label"
            :label="item.label"
            :value="item.label"
          />
        </el-select>
      </div>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="list">
      <el-table-column
        v-for="i in selectedTableList"
        :key="i.label"
        :label="i.label"
        align="center"
        :prop="i.prop"
        :row-key="i.label"
        :width="i.width"
      >
        <template #default="{ row }">
          <el-button
            v-if="i.label === '社群个数'"
            type="primary"
            link
            @click="handlePointDetails(row)"
            >{{ row.associationNum }}</el-button
          >
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />
    <pointList ref="pointListRef" />
  </div>
</template>
<script setup>
import useGlobalStore from '@/store/modules/global'
import { useOrganApiConfig } from '@/hooks/service'
import pointList from './components/pointList'
import { parseTime } from '@/utils/tools'
import { getCommunityDataListApi } from '@/api/dataReport'

const globalStore = useGlobalStore()
const cityNameOptions = computed(() => globalStore.myCityList)
const { proxy } = getCurrentInstance()
const selectState = useOrganApiConfig()

const queryRef = ref()
const list = ref([])
const loading = ref(false)
const showSearch = ref(true)
const total = ref(0)
const queryParams = ref({
  pageNum: 1,
  pageSize: 10,
  areaId: null,
  routeId: null,
  positionId: null,
  operationName: null,
  cityName: cityNameOptions.value[0],
  startTime: null,
  endTime: null
})
const cityName = computed(() => queryParams.value.cityName)

const now = new Date()
const daterange = ref([
  parseTime(new Date(now.getFullYear(), now.getMonth(), now.getDate(), 0, 0, 0, 0)),
  parseTime(new Date(), '{y}-{m}-{d}') + ' 23:59:59'
])
const tableList = ref([
  { label: '点位名称', prop: 'positionName', width: 200 },
  { label: '社群个数', prop: 'associationNum', width: 90 },
  { label: '客服人员', prop: 'operationName', width: 90 },
  { label: '成员数量', prop: 'member', width: 90 },
  { label: '新增用户数', prop: 'newClientNum', width: 90 },
  { label: '下单用户数', prop: 'buyClientNum', width: 90 },
  { label: '转化率', prop: 'conversionRate', width: 90 },
  { label: '新客下单用户数', prop: 'buyNewClientNum' },
  { label: '新客下单占比', prop: 'newClientBuyProportion' },
  { label: '复购率', prop: 'repeatedlyBuyRate' },
  { label: '退款率', prop: 'refundRate' },

  { label: '留存率', prop: 'keepRate' },
  { label: '客单价', prop: 'averagePrice' }
])
const selectedTableList = ref([])
const tableSelectVal = ref([
  '点位名称',
  '社群个数',
  '客服人员',
  '成员数量',
  '新增用户数',
  '下单用户数',
  '转化率',
  '新客下单用户数',
  '新客下单占比',
  '复购率',
  '退款率',
  '退群率',
  '留存率',
  '客单价'
])
const pointListRef = ref()
/**多选框变化 */
function tableSelectChange() {
  if (tableSelectVal.value.length < 2) {
    tableSelectVal.value.push(...['点位名称', '社群个数'])
  }
  selectedTableList.value = tableList.value.filter((item) =>
    tableSelectVal.value.includes(item.label)
  )
  console.log(selectedTableList.value)
}
tableSelectChange()
/**进入点位详情 */
function handlePointDetails(row) {
  console.log({ row })
  queryParams.value.startTime = daterange.value[0] ? daterange.value[0] : null
  queryParams.value.endTime = daterange.value[1] ? daterange.value[1] : null
  pointListRef.value.init(row, queryParams.value)
}
/***获取列表 */
function getList() {
  loading.value = true
  queryParams.value.startTime = daterange.value[0] ? daterange.value[0] : null
  queryParams.value.endTime = daterange.value[1] ? daterange.value[1] : null
  getCommunityDataListApi(queryParams.value)
    .then((res) => {
      console.log(res)
      loading.value = false
      list.value = res?.rows?.map((i) => ({
        ...i,
        conversionRate: `${i.conversionRate || 0}%`,
        newClientBuyProportion: `${i.newClientBuyProportion || 0}%`,
        repeatedlyBuyRate: `${i.repeatedlyBuyRate || 0}%`,
        refundRate: `${i.refundRate || 0}%`,
        keepRate: `${i.keepRate || 0}%`
      }))
      console.log(list.value)
      total.value = res.total || 0
    })
    .catch((err) => {
      console.log(err)
      loading.value = false
    })
}
/**查询 */
function handleQuery(type) {
  console.log(daterange.value[0], daterange.value[1])

  if (type) {
    queryRef.value.resetFields()
    daterange.value = [
      parseTime(new Date(now.getFullYear(), now.getMonth(), now.getDate(), 0, 0, 0, 0)),
      parseTime(new Date(), '{y}-{m}-{d}') + ' 23:59:59'
    ]
    radioValue.value = '当天'
    handleQuery(false)
  } else {
    queryParams.value.pageNum = 1
    getList()
  }
}
const radioValue = ref('当天')
const dateChange = () => {
  radioValue.value = ''
  handleQuery(false)
}
function handleDateRange(val) {
  const end = parseTime(new Date(), '{y}-{m}-{d}') + ' 23:59:59'
  const start = new Date()
  switch (val) {
    case '最近30天':
      start.setTime(start.getTime() - 3600 * 1000 * 24 * 29)
      daterange.value = [parseTime(start, '{y}-{m}-{d}') + ' 00:00:00', end]
      break
    case '最近7天':
      start.setTime(start.getTime() - 3600 * 1000 * 24 * 6)
      daterange.value = [parseTime(start, '{y}-{m}-{d}') + ' 00:00:00', end]
      break
    case '当天':
      daterange.value = [parseTime(start, '{y}-{m}-{d}') + ' 00:00:00', end]
      break
    default:
      break
  }
  handleQuery(false)
}
/**导出 */
function handleExport() {
  queryParams.value.startTime = daterange.value[0] ? daterange.value[0] : null
  queryParams.value.endTime = daterange.value[1] ? daterange.value[1] : null
  proxy.download(
    'operation/statistics/admin/associationDataInfo/derive',
    { ...queryParams.value },
    `社群明细列表${new Date().getTime()}.xlsx`
  )
}
getList()
</script>
<style lang="scss" scoped>
.btn-group {
  display: flex;
  align-items: center;
}
.el-radio-group {
  margin: 0 10px;
}
</style>
